package com.shy.db.controller;

import com.shy.api.model.PaymentApiData;
import com.shy.api.model.query.MerchTradeQuery;
import com.shy.db.service.ThirdPartApiService;
import com.shy.db.service.TradeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Map;

@Controller
public class TradeController {
    @Resource
    private TradeService tradeService;

    @Resource
    private Map<String, ThirdPartApiService> serviceMap;

    //接受商家的支付请求
    @GetMapping("/trade/receive")
    public String receive(MerchTradeQuery merchTradeQuery, Model model) {
        //  1. 验证签名  2. 判断商户支付配置数据是否存在
        tradeService.checkSignQueryPayInfo(merchTradeQuery);
        // 快钱支付 策略设计模式
        /**
         *  策略设计模式
         *  1.将算法封装到独立的类中
         *  2.通过某个方式选择到某个算法类
         */
        String wayCode = merchTradeQuery.getWayCode().toUpperCase();
        ThirdPartApiService thirdPartApiService = serviceMap.get(wayCode);
        if (thirdPartApiService == null) {
            throw new RuntimeException("支付服务错误");
        }
        //调用具体的算法类
        PaymentApiData paymentApiData = thirdPartApiService.invokePaymentApi(merchTradeQuery);
        //添加数据
        model.addAttribute("pay", paymentApiData);
        //指定视图
        return paymentApiData.viewName();
    }
}
